package top.linyuxb.lycloud.admin.controller;


import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import top.linyuxb.lycloud.admin.service.impl.LoginService;
import top.linyuxb.lycloud.admin.utils.ReturnT;
import top.linyuxb.lycloud.admin.web.annotation.PermissionLimit;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/29 14:43
 * @Desc:
 */
@Controller
public class IndexController {
    @Resource
    private LoginService loginService;

    @RequestMapping("/")
    public String index(Model model, HttpServletRequest request) {
        return "redirect:/conf";
    }

    @RequestMapping("/toLogin")
    @PermissionLimit(limit = false)
    public String toLogin(HttpServletRequest request) {
        if (loginService.ifLogin(request) != null) {
            return "redirect:/";
        }
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    @PermissionLimit(limit = false)
    public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response,
                                   String userName, String password, String ifRemember) {
        if (loginService.ifLogin(request) != null) {
            return ReturnT.SUCCESS;
        }
        // param
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
            return new ReturnT<>(500, "账号或密码为空");
        }
        boolean ifRem = StringUtils.isNotBlank(ifRemember) && "on".equals(ifRemember);
        // do login
        return loginService.login(response, userName, password, ifRem);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    @PermissionLimit(limit = false)
    public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response) {
        if (loginService.ifLogin(request) != null) {
            loginService.logout(request, response);
        }
        return ReturnT.SUCCESS;
    }

    @RequestMapping("/help")
    public String help() {
        return "help";
    }

}
